package cn.zhaoyan.servlet;

import cn.zhaoyan.bean.User;
import cn.zhaoyan.daoimpl.UserDaoImpl;
import cn.zhaoyan.service.Userservice;
import cn.zhaoyan.serviceimpl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(urlPatterns = "/loginServlet")
public class loginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        String yanzhengma = request.getParameter("yanzhengma");

        //获取对应的Session tomcate 会自动寻找对应的Session信息
        HttpSession session = request.getSession();
        String checkcode = (String) session.getAttribute("checkcode");
        boolean equals = yanzhengma.equals(checkcode);

        if (!equals){
            request.setAttribute("us","1");
            request.getRequestDispatcher("login.jsp").forward(request, response);

            return;
        }else {
            String name = request.getParameter("name");
            String password = request.getParameter("password");
            String role = request.getParameter("role");
            User user = new User();
            user.setName(name);
            user.setPassword(password);
            user.setRole(role);
            Userservice userServiceDl = new UserServiceImpl();
            boolean b = userServiceDl.queryServiceDl(user);

            if (b) {
                Cookie aa = new Cookie("aa", name);
                aa.setMaxAge(60*60);
                response.addCookie(aa);
                UserDaoImpl userDao = new UserDaoImpl();
                User user1 = userDao.userDao(user);
               request.getSession().setAttribute("ser1",user);
                request.getRequestDispatcher("/FindServlet").forward(request, response);

            } else {
                request.setAttribute("zz","3");

                request.getRequestDispatcher("login.jsp").forward(request, response);
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     doPost(request,response);
    }
}
